package com.hhc.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.hhc.common.Constants;
import com.hhc.model.UploadImageForm;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

@Controller
@RequestMapping("/common")
public class CommonController {

    @RequestMapping(value = "/uploadImageForAPP", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject uploadImage(@RequestBody String data) {
        JSONObject json = new JSONObject();
        try {
            UploadImageForm form = JSONObject.parseObject(data, UploadImageForm.class);
            String suffix = form.getSuffix();
            //String id = UUID.randomUUID().toString();
            String savedPath = Constants.storagePath;
            String fileName = form.getFileName() + "." + suffix;
            // 原始图
            Base64 base = new Base64();
            byte[] decode = base.decode(form.getFile());
            File dir = new File(savedPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            InputStream fin = new ByteArrayInputStream(decode);
            // 定义图片输出流
            FileOutputStream fout = new FileOutputStream(savedPath + fileName);
            // 写文件
            byte[] b = new byte[1024];
            int length = 0;
            while ((length = fin.read(b)) > 0) {
                fout.write(b, 0, length);
            }
            fout.flush();
            fout.close();

            json.put("url", fileName);
            json.put(Constants.RESULT_KEY, fileName);
            json.put(Constants.RESULT_CODE_KEY, Constants.REQUEST_SUCCESS);

        } catch (Exception e) {
            json.put(Constants.RESULT_CODE_KEY, Constants.REQUEST_FAIL);
        }
        return json;
    }
}
